import requests
import os
import json
from PyQt5 import QtCore






class InitData(QtCore.QThread):
    cloud_settings_signal = QtCore.pyqtSignal(dict)
    finished_signal = QtCore.pyqtSignal(str)
    error_signal = QtCore.pyqtSignal(str)

    def __init__(self):
        super(InitData, self).__init__()

    def pull_cloud_settings_json(self):
        url = "https://gitee.com/soaringsoul/easy_location/raw/master/settings.json"
        resq = requests.get(url)
        return resq.json()

    def refresh_local_settings(self, settings_json):
        settings_json_path = "./settings.json"
        try:
            with open(settings_json_path, 'w', encoding='utf8')as f:
                json.dump(settings_json, f)
        except Exception as e:
            self.error_signal.emit("从云端同步可用的百度ak时失败了，为保证解析服务，下次记得以管理员身份运行哦！\n错误详情:%s" % e)

    def run(self):

        # 拉取云端数据
        try:
            self.settings_json = self.pull_cloud_settings_json()
        except Exception as e:
            print("拉取云端数据失败")
            print(e)
            self.settings_json = {}

        self.cloud_settings_signal.emit(self.settings_json)
        self.refresh_local_settings(self.settings_json)
        self.finished_signal.emit("done")
